package com.sky.controller.user;

import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.result.Result;
import com.sky.service.DishFlavorService;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "用户菜品接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/list")
    @ApiOperation("菜品浏览")
    public Result<List<DishVO>> list(Long categoryId) {
        //key为 dish_分类id
        String key = "dish_" + categoryId;
        ValueOperations valueOperations = redisTemplate.opsForValue();
        List<DishVO> VoList = (List<DishVO>) valueOperations.get(key);
        //如果有缓存
        if (VoList != null && VoList.size()>0) {
            return Result.success(VoList);
        }
        VoList = new ArrayList<>();
        List<Dish> dishList = dishService.getDishList(categoryId);//查出所有的dish
        for (Dish dish : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            Long dishId = dish.getId();
            List<DishFlavor> dishFlavorList = dishFlavorService.getDishFlavorById(dishId);
            dishVO.setFlavors(dishFlavorList);
            VoList.add(dishVO);
        }
        //添加缓存
        valueOperations.set(key, VoList);
        return Result.success(VoList);
    }
}
